﻿using Quartz;

namespace AhCha.Fortunate.Api.AppCode
{
    /// <summary>
    /// Quartz ，定时执行操作
    /// </summary>
    public class QuartzHostedService : IHostedService
    {
        private readonly ISchedulerFactory _schedulerFactory;
        private IScheduler _scheduler;

        public QuartzHostedService(ISchedulerFactory schedulerFactory)
        {
            _schedulerFactory = schedulerFactory;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _scheduler = await _schedulerFactory.GetScheduler();
            await _scheduler.Start();

            // 配置和调度作业
            IJobDetail job = JobBuilder.Create<MyCustomJob>()
                .WithIdentity("myCustomJob", "group1")
                .Build();

            Quartz.ITrigger trigger = Quartz.TriggerBuilder.Create()
                .WithIdentity("myCustomJobTrigger", "group1")
                .StartNow()
                .WithSimpleSchedule(x => x
                    .WithIntervalInSeconds(10) 
                    .RepeatForever())
                .Build();

            await _scheduler.ScheduleJob(job, trigger);
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await _scheduler.Shutdown();
        }
    }


    public class MyCustomJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            Console.WriteLine("执行时间：" + DateTime.Now);
        }
    }
}
